<?php
/**
 * Created by PhpStorm.
 * User: xmy2
 * Date: 18-8-11
 * Time: 上午10:46
 */

namespace vola;


class View extends Template {

    public $assign = [];
    /**
     * @var Request
     */
    private $req;
    /**
     * @var Env
     */
    private $config;

    public function __construct()
    {
        parent::__construct();
        $this->req = Container::get('request');
        $this->config = Container::get('env');
    }

    /**
     * @param string|array $name
     * @param string $value
     */
    public function assign($name, $value = '') {
        if (is_array($name)) {
            $this->assign = array_merge($this->assign, $name);
        } else {
            $this->assign[$name] = $value;
        }
    }

    private function get_tpl($name) {
        if (pathinfo($name, PATHINFO_EXTENSION) !== '') {
            $this->tpl($name);
            return $this;
        }


        $name = explode('/', $name);

        switch (count($name)) {
            case 1:
                array_unshift($name, $this->req->module(), $this->req->controller());
                break;
            case 2:
                array_unshift($name, $this->req->module());
                break;
        }



        if ($this->config->get('tpl_path') != '') {
            $base = $this->config->get('tpl_path');
        } else {
            $base = $this->config->get('app_path');
            array_splice($name, -2, 0, 'view');
        }


        $path = rtrim($base, '\\/') . '/' . implode('/', $name) . $this->config->get('tpl_ext');

        return $path;
    }

    public function has_tpl($name) {
        if (file_exists($this->get_tpl($name))) {
            return true;
        }
        return false;
    }

    /**
     * @param string $name
     * @param array $assign
     * @return $this
     */
    public function display($name, $assign = []) {
        if (!empty($assign)) $this->assign($assign);

        $this->assign('tplconfig', Container::get('config')->get('tpl.static_tag'));


        return $this->tpl($this->get_tpl($name));
    }

    public function render() {
        ob_start();
        Loadder::includeFile($this->show(), $this->assign);
        $this->assign = [];
        return ob_get_clean();
    }
}
